import { reqcartadd } from "../../http/api";
import { reqgetgoodsinfo } from "../../http/api";
import { getUserInfo } from "./login";
import { Toast } from "antd-mobile";

const initState = {
    detailList: {},
    obj: {}
}

const types = {
    CHANGE_DETAILLIST: "DETAIL_CHANGE_LIST",
    ADD_SHOPCAR: "DETAIL_ADD_SHOPCAR",
    CHANGE_OBJ: "DETAIL_CHANGE_OBJ",
}

const reducer = (state = initState, action) => {
    switch (action.type) {
        case types.CHANGE_DETAILLIST:
            return {
                ...state,
                detailList: action.detailList
            }
        case types.CHANGE_OBJ:
            return {
                ...state,
                obj: action.obj,
            }
        default:
            return state
    }
}

export const actions = {
    changeDetaillist: detailList => ({ type: types.CHANGE_DETAILLIST, detailList }),
    reqgetgoodsinfo: () => (dispatch, getStart) => {
        let { id } = changeObj(getStart());
        reqgetgoodsinfo({ id: id }).then(res => {
            if (res.data.code === 200) {
                dispatch(actions.changeDetaillist(res.data.list))
            }
        })
    },
    changeObj: obj => ({ type: types.CHANGE_OBJ, obj }),

    /* 加入购物车 */
    addshop: ()=>(dispatch,getState)=>{
        let userInfo = getUserInfo(getState()) ;
        let {id,type} = changeObj(getState())
        reqcartadd({
            uid: userInfo.uid,
            goodsid: id,
            num: 1,
            type
        }).then(res => {
            if(res.data.code==200){
                Toast.show({
                    content:res.data.msg
                })
            }
        })
    }

}

export const getDetaillist = state => state.Detail.detailList;
export const changeObj = state => state.Detail.obj;
export const getInfo = state => state.Detail.info;

export default reducer;
